<template>
  <div class="kawaii-collections">
    <div class="kawaii-collections-header">
      <h3 class="kawaii-section-title">合集</h3>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-plus"
        v-if="isOwnSpace"
        @click="createCollection"
        class="kawaii-create-btn"
      >
        创建合集 ✨
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading && collections.length === 0"
      class="kawaii-loading-container"
    >
      <div class="kawaii-loading">
        <div class="kawaii-loading-circle"></div>
        <div class="kawaii-loading-text">加载中...</div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="collections.length === 0" class="kawaii-empty-container">
      <img
        src="@/assets/icons/empty-box.svg"
        alt="暂无合集"
        class="kawaii-empty-icon"
      />
      <p class="kawaii-empty-text">暂无合集 (ノ_＜)</p>
      <p v-if="isOwnSpace" class="kawaii-empty-hint">
        创建合集可以将相关视频组织在一起，方便观看和管理 (⌒▽⌒)♪
      </p>
    </div>

    <!-- 合集列表 -->
    <div v-else class="kawaii-collections-grid">
      <div
        v-for="collection in collections"
        :key="collection.id"
        class="kawaii-collection-item"
        @click="viewCollection(collection)"
      >
        <div class="kawaii-collection-cover">
          <div class="kawaii-collection-cover-stack">
            <img
              v-for="(video, index) in collection.covers"
              :key="index"
              :src="video"
              :style="{
                zIndex: collection.covers.length - index,
                right: `${index * 5}px`,
                top: `${index * 5}px`,
              }"
              alt="合集封面"
              class="kawaii-stack-image"
            />
          </div>
          <div class="kawaii-collection-info-overlay">
            <div class="kawaii-collection-video-count">
              <i class="el-icon-video-camera"></i>
              {{ collection.videoCount }}个视频
            </div>
            <div class="kawaii-collection-play-count">
              <i class="el-icon-video-play"></i>
              {{ formatCount(collection.playCount) }}
            </div>
          </div>
        </div>
        <div class="kawaii-collection-info">
          <div class="kawaii-collection-title">{{ collection.title }}</div>
          <div class="kawaii-collection-desc">{{ collection.description }}</div>
          <div class="kawaii-collection-time">
            更新于：{{ collection.updateTime }}
          </div>
        </div>
        <div class="kawaii-collection-actions" v-if="isOwnSpace">
          <el-dropdown @command="handleCommand" trigger="hover">
            <span class="kawaii-el-dropdown-link">
              <i class="el-icon-more"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :command="{ type: 'edit', id: collection.id }"
                >
                  编辑
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ type: 'delete', id: collection.id }"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="kawaii-pagination-container" v-if="collections.length > 0">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 创建/编辑合集对话框 -->
    <el-dialog
      v-model="collectionDialogVisible"
      :title="isEditing ? '编辑合集' : '创建合集'"
      width="500px"
      class="kawaii-dialog"
    >
      <el-form :model="collectionForm" label-width="80px">
        <el-form-item label="标题">
          <el-input
            v-model="collectionForm.title"
            placeholder="请输入合集标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="collectionForm.description"
            placeholder="请输入合集描述"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="kawaii-collection-cover-uploader"
            action="#"
            :auto-upload="false"
            list-type="picture-card"
            :limit="3"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="kawaii-upload-tip">可上传1-3张图片作为合集封面 ✨</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button @click="collectionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCollection">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      class="kawaii-dialog"
    >
      <span>确定要删除该合集吗？此操作不可撤销。</span>
      <template #footer>
        <span class="kawaii-dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'

const props = defineProps({
  userId: {
    type: [String, Number],
    required: true,
  },
})

const router = useRouter()
const userStore = useUserStore()

// 是否是用户自己的空间
const isOwnSpace = computed(() => {
  return props.userId === userStore.id
})

// 状态变量
const collections = ref([])
const loading = ref(true)
const total = ref(0)
const pageSize = ref(12)
const currentPage = ref(1)
const collectionDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEditing = ref(false)
const selectedCollectionId = ref(null)

// 合集表单
const collectionForm = ref({
  id: null,
  title: '',
  description: '',
  covers: [],
})

// 使用二次元图片作为封面
const coverImages = [
  '/src/assets/anime/images/banner1.png',
  '/src/assets/anime/images/banner2.png',
  '/src/assets/anime/images/banner3.png',
  '/src/assets/anime/images/banner4.png',
  '/src/assets/anime/images/banner5.png',
  '/src/assets/anime/images/banner6.png',
  '/src/assets/anime/images/banner7.png',
  '/src/assets/anime/images/banner8.png',
  '/src/assets/anime/images/banner9.png',
  '/src/assets/anime/images/banner10.png',
  '/src/assets/anime/images/banner11.png',
  '/src/assets/anime/images/banner12.png',
  '/src/assets/anime/images/banner13.png',
  '/src/assets/anime/images/banner14.png',
  '/src/assets/anime/images/banner15.png',
]

// 格式化数字
const formatCount = (count) => {
  if (!count && count !== 0) return '-'
  if (count === 0) return '-'

  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 生成模拟合集数据
const generateMockCollections = (page: number, pageSize: number) => {
  const mockCollections = []

  // 二次元相关的合集标题
  const animeTitles = [
    '宫崎骏动画合集',
    '国产动漫精选',
    '经典机甲作品',
    '热血少年漫改',
    '治愈系动画片段',
    '催泪动漫场景',
    '声优歌曲精选',
    '新海诚的唯美世界',
    '科幻动画探索',
    '奇幻冒险系列',
    '青春校园物语',
    '恋爱番推荐',
    '悬疑推理动画',
    '美食番合集',
    '异世界转生系列',
  ]

  // 合集描述
  const collectionDescriptions = [
    '精选最经典的场景和音乐，带你回味难忘的动画之旅',
    '这些作品将带你进入奇幻的二次元世界',
    '收录了所有让人热血沸腾的精彩场景',
    '每一帧都是艺术，每一刻都是感动',
    '沉浸在这些精心挑选的画面中，感受创作者的用心',
    '从不同角度欣赏动漫的魅力',
    '让我们一起重温那些难忘的瞬间',
    '独特的艺术风格和故事讲述方式',
    '探索不同时期的经典作品',
    '每一部都值得反复观看和品味',
  ]

  // 计算起始索引
  const startIndex = (page - 1) * pageSize

  for (let i = 0; i < pageSize; i++) {
    const id = startIndex + i + 1

    // 随机选择1-3张图片作为封面
    const coverCount = Math.floor(Math.random() * 3) + 1
    const covers = []
    for (let j = 0; j < coverCount; j++) {
      const bannerIndex = Math.floor(Math.random() * 15) + 1
      covers.push(`/src/assets/anime/images/banner${bannerIndex}.png`)
    }

    // 随机选择一个标题和描述
    const title = animeTitles[Math.floor(Math.random() * animeTitles.length)]
    const description =
      collectionDescriptions[
        Math.floor(Math.random() * collectionDescriptions.length)
      ]

    // 随机生成视频数量和播放量
    const videoCount = Math.floor(Math.random() * 15) + 3 // 3-18个视频
    const playCount = Math.floor(Math.random() * 500000) + 1000 // 1000-501000的播放量

    // 创建时间递减，使得排序更真实
    const date = new Date()
    date.setDate(date.getDate() - (id % 30)) // 最近30天内的某一天

    mockCollections.push({
      id: id,
      title: title,
      description: description,
      covers: covers,
      videoCount: videoCount,
      playCount: playCount,
      updateTime: formatDate(date),
    })
  }

  return mockCollections
}

// 获取随机标题
const getRandomTitle = () => {
  const titles = [
    '年度精选合集',
    '教程系列',
    '游戏实况全集',
    '电影解说合集',
    '美食vlog合集',
    '旅行日记',
    '编程学习系列',
    '健身指南合集',
    '音乐现场精选',
    '动漫混剪系列',
  ]

  return titles[Math.floor(Math.random() * titles.length)]
}

// 格式化日期
const formatDate = (date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 小于一天，显示x小时前
  if (diff < 86400000) {
    // 24 * 60 * 60 * 1000
    const hours = Math.floor(diff / 3600000)
    return hours > 0 ? `${hours}小时前` : '刚刚'
  }

  // 小于一个月，显示x天前
  if (diff < 2592000000) {
    // 30 * 24 * 60 * 60 * 1000
    return `${Math.floor(diff / 86400000)}天前`
  }

  // 否则显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取合集数据
const fetchCollections = async () => {
  loading.value = true

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 模拟合集数据
    const mockCollections = generateMockCollections(
      currentPage.value,
      pageSize.value,
    )
    collections.value = mockCollections

    // 总数设为30
    total.value = 30
  } catch (error) {
    console.error('获取合集数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchCollections()
}

// 查看合集
const viewCollection = (collection) => {
  router.push(`/space/${props.userId}/collection/${collection.id}`)
}

// 创建合集
const createCollection = () => {
  isEditing.value = false
  collectionForm.value = {
    id: null,
    title: '',
    description: '',
    covers: [],
  }
  collectionDialogVisible.value = true
}

// 编辑合集
const editCollection = (id) => {
  isEditing.value = true

  // 查找要编辑的合集
  const collection = collections.value.find((c) => c.id === id)
  if (collection) {
    collectionForm.value = {
      id: collection.id,
      title: collection.title,
      description: collection.description,
      covers: [...collection.covers],
    }
    collectionDialogVisible.value = true
  }
}

// 保存合集
const saveCollection = async () => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    if (isEditing.value) {
      // 模拟更新合集
      const index = collections.value.findIndex(
        (c) => c.id === collectionForm.value.id,
      )
      if (index !== -1) {
        collections.value[index] = {
          ...collections.value[index],
          title: collectionForm.value.title,
          description: collectionForm.value.description,
        }
      }
    } else {
      // 模拟创建合集
      const randomCoverIndex = Math.floor(Math.random() * coverImages.length)
      const newCollection = {
        id: Date.now(),
        title: collectionForm.value.title,
        description: collectionForm.value.description,
        covers: [coverImages[randomCoverIndex]],
        videoCount: 0,
        playCount: 0,
        updateTime: '刚刚',
      }

      // 添加到列表开头
      collections.value.unshift(newCollection)
    }

    // 关闭对话框
    collectionDialogVisible.value = false
  } catch (error) {
    console.error('保存合集失败:', error)
  }
}

// 删除合集对话框
const showDeleteDialog = (id) => {
  selectedCollectionId.value = id
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    // 从列表中移除
    collections.value = collections.value.filter(
      (c) => c.id !== selectedCollectionId.value,
    )

    // 关闭对话框
    deleteDialogVisible.value = false
    selectedCollectionId.value = null
  } catch (error) {
    console.error('删除合集失败:', error)
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command.type === 'edit') {
    editCollection(command.id)
  } else if (command.type === 'delete') {
    showDeleteDialog(command.id)
  }
}

// 初始化
onMounted(() => {
  fetchCollections()
})
</script>

<style scoped lang="scss">
.kawaii-collections {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.kawaii-collections-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 12px 20px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
}

.kawaii-section-title {
  font-size: 20px;
  font-weight: bold;
  color: #7c5479;
  margin: 0;
  position: relative;
  display: inline-block;

  &::after {
    content: '';
    position: absolute;
    bottom: -5px;
    left: 0;
    width: 100%;
    height: 3px;
    background: linear-gradient(to right, #fe4ea4, #ff9fcf);
    border-radius: 3px;
  }
}

.kawaii-create-btn {
  background: linear-gradient(to right, #fe4ea4, #ff9fcf);
  border: none;
  border-radius: 20px;
  color: white;
  padding: 8px 16px;
  transition: all 0.3s;
  font-weight: bold;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(254, 78, 164, 0.3);
  }
}

.kawaii-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.kawaii-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.kawaii-loading-circle {
  width: 50px;
  height: 50px;
  border: 4px solid #ffcbe3;
  border-top-color: #fe4ea4;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.kawaii-loading-text {
  color: #7c5479;
  font-size: 16px;
  font-weight: bold;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.kawaii-empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 10px rgba(255, 182, 193, 0.2);
  border: 2px solid rgba(255, 182, 193, 0.3);
  backdrop-filter: blur(5px);
}

.kawaii-empty-icon {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  animation: float 3s infinite ease-in-out;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}

.kawaii-empty-text {
  font-size: 18px;
  color: #7c5479;
  font-weight: bold;
  margin-bottom: 10px;
}

.kawaii-empty-hint {
  font-size: 14px;
  color: #99809d;
  text-align: center;
  max-width: 280px;
}

.kawaii-collections-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.kawaii-collection-item {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 15px rgba(255, 182, 193, 0.25);
  border: 2px solid rgba(255, 182, 193, 0.3);
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(255, 182, 193, 0.4);

    .kawaii-collection-cover::after {
      opacity: 0.5;
    }

    .kawaii-collection-title {
      color: #fe4ea4;
    }
  }
}

.kawaii-collection-cover {
  height: 180px;
  position: relative;
  overflow: hidden;
  background-color: #f9f0f5;

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to bottom,
      rgba(255, 182, 193, 0.1),
      rgba(255, 105, 180, 0.2)
    );
    opacity: 0;
    transition: opacity 0.3s;
  }
}

.kawaii-collection-cover-stack {
  width: 100%;
  height: 100%;
  position: relative;
}

.kawaii-stack-image {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  transition: all 0.3s;
}

.kawaii-collection-info-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  z-index: 5;
  display: flex;
  justify-content: space-between;
}

.kawaii-collection-video-count,
.kawaii-collection-play-count {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.kawaii-collection-info {
  padding: 15px;
}

.kawaii-collection-title {
  font-size: 16px;
  font-weight: bold;
  color: #7c5479;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  width: 100%;
  white-space: normal;
  transition: all 0.3s;
}

.kawaii-collection-desc {
  font-size: 12px;
  color: #99809d;
  margin-bottom: 8px;
  height: 36px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.kawaii-collection-time {
  font-size: 12px;
  color: #b5a9d4;
}

.kawaii-collection-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);

  &:hover {
    background-color: rgba(255, 255, 255, 1);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
  }
}

.kawaii-el-dropdown-link {
  color: #7c5479;
  cursor: pointer;
  display: block;
  text-align: center;
}

.kawaii-pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination.is-background) {
    .el-pager li:not(.disabled).active {
      background-color: #fe4ea4;
    }

    .el-pager li:not(.disabled):hover {
      color: #fe4ea4;
    }

    .btn-prev,
    .btn-next {
      &:hover {
        color: #fe4ea4;
      }
    }
  }
}

.kawaii-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(to right, #ffcbe3, #ffd6ff);
    padding: 15px 20px;
    border-radius: 10px 10px 0 0;
  }

  :deep(.el-dialog__title) {
    color: #7c5479;
    font-weight: bold;
  }

  :deep(.el-dialog__body) {
    background-color: #fff;
    padding: 20px;
    color: #7c5479;
  }

  :deep(.el-dialog__footer) {
    background-color: #fff;
    padding: 10px 20px 20px;
    border-radius: 0 0 10px 10px;
  }

  :deep(.el-form-item__label) {
    color: #7c5479;
  }
}

.kawaii-collection-cover-uploader {
  :deep(.el-upload--picture-card) {
    border-color: #ffcbe3;
    background-color: rgba(255, 200, 227, 0.1);
    border-style: dashed;

    &:hover {
      border-color: #fe4ea4;
    }
  }
}

.kawaii-upload-tip {
  font-size: 12px;
  color: #99809d;
  margin-top: 5px;
}

.kawaii-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;

  :deep(.el-button) {
    border-radius: 20px;
  }

  :deep(.el-button--default) {
    border-color: #b5a9d4;
    color: #7c5479;

    &:hover {
      border-color: #c9a0dc;
      background-color: rgba(201, 160, 220, 0.1);
    }
  }

  :deep(.el-button--primary) {
    background: linear-gradient(to right, #fe4ea4, #ff9fcf);
    border: none;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(254, 78, 164, 0.3);
    }
  }

  :deep(.el-button--danger) {
    background: linear-gradient(to right, #ff6a88, #ff99ac);
    border: none;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(255, 106, 136, 0.3);
    }
  }
}

@media (max-width: 768px) {
  .kawaii-collections-grid {
    grid-template-columns: 1fr;
  }
}
</style>
